let last_kw = '';
let max_sug_len = 1; //搜索建议最短触发长度

function searchC(){
    let kw =$('#search_input').val();
    if (kw == last_kw) return;
    last_kw = kw;
    if (!kw || kw.length < max_sug_len) {
        close_sug();
        return;
    }

    $.ajax({
        url: 'api/course/lists',
        type: 'get',
        data: {key_word:kw},
        dataType: 'json',
        timeout: 2000,
        success: function (res) {
            if (res.code == 0) {
                let suggest = $('#suggest');
                if (!res.data || res.data.length==0) {
                    suggest.css('display','none');
                    return;
                }
                let html = '';
                res.data.forEach(function (v) {
                    let url = routes.detail.replace('ids', v.id);
                    html += '<li><a href="'+url+'">' + v.name + '('+v.category_info.name+')</a></li>';
                });
                $('#suglist').html(html);
                suggest.css('display','block');
            } else {
                tispFun(res.msg);
            }
        },
        error: function () {
            tispFun('网络错误,稍后再试');
        }
    });

}

function get_suggest() {
    var kw = document.getElementById('search_input').value;
    if (kw == last_kw) return;
    last_kw = kw;
    if (!kw || kw.length < max_sug_len) {
        close_sug();
        return;
    }
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'http://sugs.m.sm.cn/web?t=w&uc_param_str=dnnwnt&scheme=http&fr=android&bid=1&q=' + encodeURIComponent(kw) + '&_=' + new Date().getTime() + '&callback=jsonp3';
    var head = document.querySelector('head');
    script.onload = function () {
        head.removeChild(script);
    };
    head.appendChild(script);
}
function jsonp3(res) {
    var suggest = document.getElementById('suggest');
    if (!res.r || !res.r.length) {
        suggest.style.display = 'none';
        return;
    }
    var html = '';
    res.r.forEach(function (v) {
        html += '<li>' + v.w + '</li>';
    });
    document.getElementById('suglist').innerHTML = html;
    suggest.style.display = 'block';
}

function close_sug() {
    last_kw = '';
    $('#suggest').css('display','none')
}
